package cn.globalph.housekeeper.service

import android.app.Service
import android.content.Context
import android.content.Intent
import android.media.AudioManager
import android.media.AudioManager.STREAM_MUSIC
import android.media.MediaPlayer
import android.media.SoundPool
import android.os.IBinder
import android.os.Vibrator
import android.util.Log
import cn.globalph.housekeeper.R

class AlarmService : Service(),AudioManager.OnAudioFocusChangeListener{
    override fun onAudioFocusChange(focusChange: Int) {

    }


    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        playMusic()
        vibrate()
        return super.onStartCommand(intent, flags, startId)
    }



    private fun vibrate(){
        var vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        var patton = LongArray(2)
        patton[0] = 10000
        patton[1] = 1000
         vibrator.vibrate(1000)
//
////        isIgnoreBatteryOption(this)
    }

    private fun playMusic(){
        val audioManager: AudioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
        val maxVolume = audioManager.getStreamMaxVolume(STREAM_MUSIC)
        val currentVolume = audioManager.getStreamVolume(STREAM_MUSIC)
        audioManager.requestAudioFocus(
            this,
            AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE
        )
        audioManager.setStreamVolume(STREAM_MUSIC,(maxVolume/2f).toInt(),0)
        val player = MediaPlayer.create(this,R.raw.sound)
        player.setOnCompletionListener {
            audioManager.abandonAudioFocus (this)
            audioManager.setStreamVolume(STREAM_MUSIC,currentVolume,0)
            stopSelf()
        }
        player.start()
    }
}